<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // eg: 将被代理的类绑定到一个全局实例集合，让所有的实例都被添加到这个集合中

        const userList = []

        class User {
            constructor (name) {
                this.name = name
            }
        }

        const proxy = new Proxy(User, {
            construct () {
                const newUser = Reflect.construct(...arguments)
                userList.push(newUser)
                return newUser
            }
        })

        new proxy('huawei')
        new proxy('xiaomi')
        new proxy('apple')

        console.log(userList)

        // 另外还可以把集合绑定到一个事件分派程序，每次插入新实例都会发送消息
        const userList1 = []

        function emit(newValue) {
            console.log(newValue)
        }

        const proxy1 = new Proxy(userList1, {
            set(target, property, value, receiver) {
                const res = Reflect.set(...arguments)
                if (res) {
                    emit(Reflect.get(target, property, receiver))
                }
                return res
            }
        }) 
        proxy1.push('xiaomi')
        proxy1.push('huawei')
    </script>
</body>
</html>